package com.gzw.scm.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.JBAdapter;
import com.gzw.scm.base.NewBaseActivity;
import com.gzw.scm.bean.BDInfo;
import com.gzw.scm.bean.CodeInfo;
import com.gzw.scm.bean.SCBDInfo;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/8/11.
 */

public class JCBDActivity extends NewBaseActivity {

    private Context mContext;
    private RecyclerView mRecyclerView;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll;
    private boolean isCheck = false;
    private ProgressDialog mProgressDialog;
    private String bdzzxbh=null,bdxm=null;
    private DBManager dbManager;
    private SwipeRefreshLayout mSwipeLayout;
    private String dataType;
    private List<BDInfo> ls_bdInfo,ls_allbdInfo,lsbh;
    private JBAdapter jbAdapter;
    private List<SCBDInfo> ls_scbd;
    private View view;
    private Toolbar toolbar;
    private Logger log;


    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_jcbd);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head2).findViewById(R.id.tv_selectAll);
        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("解除绑定");
        setSupportActionBar(toolbar);

        dataType="rdcjd";
        dbManager=new DBManager(mContext);
        ls_bdInfo = new ArrayList<>();
        ls_allbdInfo= new ArrayList<>();
        ls_scbd= new ArrayList<>();
        lsbh= new ArrayList<>();

        /**
         * 刷新框架
         * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        setListData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
    }

    /**
     * 显示信息
     * */
    private void setListData(){
        ls_bdInfo = dbManager.SelectBDInfo(MyApplication.getUserInfo().getDid(),dataType);
        if(ls_bdInfo.size()==0||ls_bdInfo==null){

        }else{
            ls_allbdInfo.clear();
            ls_allbdInfo.addAll(ls_bdInfo);
        }

        jbAdapter = new JBAdapter(ls_bdInfo,mContext);
        mRecyclerView.setAdapter(jbAdapter);


        jbAdapter.setOnRecyclerViewListener(position ->  {

                if(JBAdapter.getIsSelected().get(position)==true){
                    JBAdapter.getIsSelected().put(position, false);
                    jbAdapter.notifyDataSetChanged();
                }else{
                    JBAdapter.getIsSelected().put(position, true);
                    jbAdapter.notifyDataSetChanged();
                }

        });
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    sendData();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bdInfo != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bdInfo.size(); i++) {
                                JBAdapter.getIsSelected().put(i, true);
                            }
                            jbAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bdInfo.size(); i++) {
                                if (JBAdapter.getIsSelected().get(i)) {
                                    JBAdapter.getIsSelected().put(i, false);
                                }
                            }
                            jbAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }


    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        panduan(code);
        return code;
    };

    /**
     * 判断扫描条码类型
     * */

    private void panduan(String message){
        if(message.contains("SSID")){
            CodeInfo codeInfo = JsonUtil.getPerson(message, CodeInfo.class);
            String code = codeInfo.getNO();
            GetBDinfoTask getBDinfoTask = new GetBDinfoTask();
            getBDinfoTask.execute(code,"");
        }else if(message.substring(0,1).equals("P")&&message.length()==11){
            GetBDinfoTask getBDinfoTask = new GetBDinfoTask();
            getBDinfoTask.execute("",message);
        }else{
            T.showShort(mContext,"该码不符合规则");
        }
    }

    private void sendData(){

        lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bdInfo.size(); i++) {
            if (jbAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bdInfo.get(i));
            }
        }

        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要解绑的信息");
            return;
        }
        ls_scbd = new ArrayList<>();
        for (BDInfo bdInfo : lsbh) {
            SCBDInfo scbdInfo = new SCBDInfo();
            scbdInfo.setBelongid(String.valueOf(MyApplication.getUserInfo().getBelongId()));
            scbdInfo.setDept(String.valueOf(MyApplication.getUserInfo().getDid()));
            scbdInfo.setTboxid(bdInfo.getZzxbh());
            scbdInfo.setOrdnoid(bdInfo.getXm());
            ls_scbd.add(scbdInfo);
        }
        String json = JsonUtil.toJson(ls_scbd);
        SendBBTask sendBBTask  = new SendBBTask();
        sendBBTask.execute(json);


    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
        List<BDInfo> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bdInfo.size(); i++) {
            if (jbAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bdInfo.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的绑定信息!");
        }else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<BDInfo> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个绑定信息吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
                dbManager.deleteBDInfo(ls_bh,MyApplication.getUserInfo().getDid(),dataType);
                setListData();

        });
        builder.setNegativeButton("取消", (dialog, which) -> {

        });
        builder.show();
    }

    /**
     * 查询绑定信息的数据请求
     */

    public class GetBDinfoTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {
            SCBDInfo scbdInfo = new SCBDInfo();
            scbdInfo.setDept(String.valueOf(MyApplication.getUserInfo().getDid()));
            scbdInfo.setBelongid(String.valueOf(MyApplication.getUserInfo().getBelongId()));
            scbdInfo.setTboxid(params[0]);
            scbdInfo.setOrdnoid(params[1]);
            String json = JsonUtil.toJson(scbdInfo);
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "See"), "strJson=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {

            try {
                if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            String jgStr = JsonUtil.getMsg(result, "result").toString();

            if(result.contains("chuku")){
                String chuku = JsonUtil.getMsg(result, "chuku").toString();
                if(chuku.equals("1")){
                    showAlertDialog("该周转箱已出库，不能解绑");
                    return;
                }
            }

            if(jgStr.equals("true")&&result.contains("tboxid")&&result.contains("ordnoid")){
                bdzzxbh = JsonUtil.getMsg(result, "tboxid").toString();
                bdxm = JsonUtil.getMsg(result, "ordnoid").toString();
                BDInfo bdInfo = new BDInfo();
                bdInfo.setZzxbh(bdzzxbh);
                bdInfo.setXm(bdxm);
                bdInfo.setZt("1");
                panduanBDInfo(bdInfo);
            }else{
                showAlertDialog("该码未绑定");
                return;
            }
            }catch (Exception e) {
                log.info("See:"+e.toString()+"/"+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**
     * 判断绑定信息是否已扫描
     * */
    private void panduanBDInfo(BDInfo bdInfo){
        BDInfo bdInfo1 = dbManager.SelectBDInfoByzzx(bdInfo.getZzxbh(),MyApplication.getUserInfo().getDid(),dataType);
        if(bdInfo1.getZzxbh()!=null){
            T.showShort(mContext,"该绑定信息已扫描");
            return;
        }else{
            dbManager.addBdinfo(bdInfo,dataType,MyApplication.getUserInfo().getDid(),"1");
            setListData();
        }
    }

    /**
     * 上传解绑的数据请求
     * 解绑
     */

    public class SendBBTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {

            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "unBind"), "strJson=" + params[0]);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {

            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            String ErrStr="";
            String jgStr = JsonUtil.getMsg(result, "result").toString();
            if(result.contains("Err")){
                ErrStr= JsonUtil.getMsg(result, "Err").toString();
            }
            if(ErrStr==""||ErrStr.length()==0){
                showAlertDialog("解绑成功"+ls_scbd.size()+"个周转箱");
                dbManager.deleteBDInfo(lsbh,MyApplication.getUserInfo().getDid(),dataType);

            }else{
                String[ ] str_Array = ErrStr.split(",");
                List<String> ls = new ArrayList<>();
                for (int i=0;i<str_Array.length;i++){
                    ls.add(str_Array[i]);
                    for(int a=0;a<lsbh.size();a++){
                        if(lsbh.get(a).getZzxbh().equals(str_Array[i])){
                            lsbh.remove(a);
                        }
                    }
                }
                dbManager.deleteBDInfo(lsbh,MyApplication.getUserInfo().getDid(),dataType);
                showAlertDialog("解绑成功"+lsbh.size()+"个周转箱，"+ErrStr+"未解绑成功");
            }
            setListData();

            }catch (Exception e) {
                log.info("unBind:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }

        }
    }
}